package com.wyh.service.serviceImpl.g3serviceimpl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyh.domain.po.g3po.Feeclassification;
import com.wyh.mapper.g3mapper.FeeclassificationMapper;
import com.wyh.service.g3service.FeeclassificationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FeeclassificationServiceImpl extends ServiceImpl<FeeclassificationMapper, Feeclassification>
        implements FeeclassificationService {

    private static final Logger logger = LoggerFactory.getLogger(FeeclassificationServiceImpl.class);

    @Autowired
    private FeeclassificationMapper feeclassificationMapper;

    /**
     * 获取所有费用分类的树形结构
     */
    @Override
    public List<Map<String, Object>> getTreeStructure() {
        List<Feeclassification> allClassifications = feeclassificationMapper.selectList(null);
        logger.info("All Classifications: {}", allClassifications); // 添加日志
        return buildTree(allClassifications, null); // 从根节点开始构建树形结构
    }

    private List<Map<String, Object>> buildTree(List<Feeclassification> allClassifications, Integer parentId) {
        // 初始化树形结构列表
        List<Map<String, Object>> tree = new ArrayList<>();

        // 遍历所有分类
        for (Feeclassification classification : allClassifications) {
            // 检查当前分类是否属于当前父节点（根节点或者子节点）
            if ((classification.getParentid() == null && parentId == null) ||
                    (classification.getParentid() != null && classification.getParentid().equals(parentId)) ||
                    (classification.getParentid() != null && classification.getParentid() == 0 && parentId == null)) {

                // 创建一个节点表示当前分类
                Map<String, Object> node = new HashMap<>();
                node.put("id", classification.getId());
                node.put("parentid", classification.getParentid());
                node.put("name", classification.getName());

                // 递归调用，获取当前分类的子分类
                List<Map<String, Object>> children = buildTree(allClassifications, classification.getId());
                if (!children.isEmpty()) {
                    // 如果有子分类，添加到当前节点
                    node.put("children", children);
                }
                // 将当前节点添加到树形结构列表中
                tree.add(node);
            }
        }
        // 返回树形结构
        return tree;
    }

    /**
     * 添加分类
     */
    @Override
    public void addFeeclassification(Feeclassification feeclassification) {
        // 检查是否是添加根节点
        if (feeclassification.getParentid() == null || feeclassification.getParentid() == 0) {
            // 根节点不允许添加
            throw new IllegalArgumentException("无法添加主节点");
        }

        // 检查父级分类是否存在
        Feeclassification parentClassification = feeclassificationMapper.selectById(feeclassification.getParentid());
        if (parentClassification == null) {
            throw new IllegalArgumentException("父级分类不存在");
        }

        // 如果父级分类不是根节点，则检查是否已经添加了费项
        if (feeclassification.getParentid() != 0) {
            if (hasFeeItems(feeclassification.getParentid())) {
                // 父级分类已经添加了费项，不能再添加子分类
                throw new IllegalArgumentException("父级分类已添加费项，不能再添加子分类");
            }
        }

        // 检查重名
        if (feeclassificationMapper.countByNameAndParentId(feeclassification.getName(), feeclassification.getParentid()) > 0) {
            throw new IllegalArgumentException("同一父级分类下不允许重名");
        }

        feeclassificationMapper.addFeeclassification(feeclassification);
    }

    /**
     * 删除分类
     */
    @Override
    public void deleteFeeclassification(Integer id) {
        if (hasChildren(id) || hasFeeItems(id)) {
            throw new IllegalArgumentException("此分类有关联费项或子分类，不能删除");
        }
        feeclassificationMapper.deleteById(id);
    }

    /**
     * 判断分类是否存在子类
     */
    @Override
    public boolean hasChildren(Integer id) {
        return feeclassificationMapper.hasChildren(id);
    }

    /**
     * 判断分类是否存在费项
     */
    @Override
    public boolean hasFeeItems(Integer id) {
        return feeclassificationMapper.hasFeeItems(id);
    }

    /**
     * 编辑分类
     */
    @Override
    public void editFeeclassification(Integer id, Feeclassification feeClassification) {
        // 检查重名
        if (feeclassificationMapper.countByNameAndParentIdExcludingId(feeClassification.getName(), feeClassification.getParentid(), id) > 0) {
            throw new IllegalArgumentException("同一父级分类下不允许重名");
        }

        feeClassification.setId(id);
        feeclassificationMapper.updateFeeclassification(feeClassification);
    }

    /**
     * 搜索分类
     */
    @Override
    public List<Feeclassification> searchFeeclassification(String keyword) {
        return feeclassificationMapper.searchByName(keyword);
    }
}
